﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using KL.UFrame.Api.Extensions;
using KL.UFrame.Core.Result;
using KL.UFrame.Data.Business;
using KL.UFrame.Data.Models;
using Microsoft.AspNet.Identity;

namespace KL.UFrame.Api.ApiControllers
{
    [RoutePrefix("api/Performance")]
    public class PerformanceController : K9ApiBaseController
    {
        private IPerformanceBusiness _business;

        public PerformanceController(IPerformanceBusiness business)
        {
            _business = business;
        }

        [Route("Create")]
        public async Task<ResultMessage> CreateAsync(PerformanceModel model)
        {
            if (!ModelState.IsValid)
            {
                return ModelState.ToResultMessage();
            }
            model.Enabled = false;
            model.CreateId = User.Identity.GetUserId();
            model.CreateTime=DateTime.Now;
            
            var result = await _business.CreateAsync(model);
            return new ResultMessage(result);
        }

        [Route("Update")]
        public async Task<ResultMessage> UpdateAsync(PerformanceModel model)
        {
            ModelState.Remove("Thumb");
            ModelState.Remove("ImageUrl");
            if (!ModelState.IsValid)
            {
                return ModelState.ToResultMessage();
            }
            model.UpdateId = User.Identity.GetUserId();
            model.UpdateTime = DateTime.Now;

            var result = await _business.UpdateAsync(model);
            return new ResultMessage(result);
        }

        [Route("Content")]
        public async Task<ResultMessage<bool>> SetContentAsync(int id, string content)
        {
            return new ResultMessage<bool>(await _business.SetContentAsync(id, content));
        }

        [HttpPost]
        [Route("Delete")]
        public async Task<ResultMessage<bool>> DeleteAsync(int id)
        {
            return new ResultMessage<bool>(await _business.DeleteAsync(id));
        }

        [HttpPost]
        [Route("Resume")]
        public async Task<ResultMessage<bool>> ResumeAsync(int id)
        {
            return new ResultMessage<bool>(await _business.ResumeAsync(id));
        }

        [HttpGet]
        [Route("Search")]
        public async Task<ResultMessage<List<PerformanceModel>>> SearchAsync(string title, DateTime start, DateTime end,
            int pageIndex,
            int pageSize)
        {
            return
                await
                    _business.SearchAsync(title, start.ToBeginning(), end.ToEnd(), pageIndex < 1 ? 1 : pageIndex,
                        pageSize < 1 ? 10 : pageSize);
        }

        public async Task<ResultMessage<PerformanceModel>> GetAsync(int id)
        {
            return new ResultMessage<PerformanceModel>(await _business.GetAsync(id));
        }
    }
}
